class Plan < ApplicationRecord
  # has_many :payment_requests, dependent: :destroy
  has_many :targets, dependent: :delete_all
  has_many :academic_partitions, through: :targets
  has_many :charges, dependent: :delete_all
  has_many :payment_requests

  validates :name, presence: { message: '缴费计划名称不能为空' },
            length: {minimum: 2, maximum: 50, message: '名称的长度应在2至50字符之间'},
            uniqueness: { message: '缴费计划名称已被使用' }

  # validates :active, uniqueness: { message: '已存在缴费中的项目' },
  #                    allow_nil: true

  def update_with_colleges!(college_ids)
    transaction do
      save!
      existing_college_ids = academic_partitions.pluck(:id)

      if !active? && paid_count.zero?
        college_ids_to_delete = existing_college_ids - college_ids
        tgts = targets.where(academic_partition_id: college_ids_to_delete)
        klass_ids = AcademicPartitionHierarchy.where(ancestor_id: tgts.map(&:academic_partition_id))
                        .where(distance: 3)
                        .pluck(:descendant_id)
        n = payment_requests.where(klass: klass_ids).delete_all
        decrement!(:payment_requests_count, n)
        targets.delete_all
        reload
      end

      extra_college_ids = college_ids - existing_college_ids
      College.where(id: extra_college_ids).each do |college|
        targets.create!(academic_partition: college)
      end
    end
  end

end